<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\admin\model\vppz\VipOrder;
use app\admin\model\vppz\VipPackage;
use \app\admin\model\vppz\User as UserModel;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        return $this->view->fetch();
    }
    public function getmsg(){
        if (isset($_GET['echostr'])) {
            $this->valid();
        }else{
            $this->responseMsg();
        }

    }
    public function valid(){
        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        // 获取微信发送的GET参数
        $signature = isset($_GET['signature']) ? $_GET['signature'] : '';
        $timestamp = isset($_GET['timestamp']) ? $_GET['timestamp'] : '';
        $nonce = isset($_GET['nonce']) ? $_GET['nonce'] : '';
        $echostr = isset($_GET['echostr']) ? $_GET['echostr'] : '';

        // 你的小程序消息推送配置的Token（在微信公众平台配置的）
        $token = 'wxpay'; // 替换为你在微信公众平台配置的Token
        // 验证签名
        if ($this->checkSignature($token, $timestamp, $nonce, $signature)) {
            // 签名验证通过，返回echostr参数内容
            echo $echostr;
            exit;
        } else {
            // 签名验证失败
            header('HTTP/1.1 403 Forbidden');
            echo "签名验证失败";
            exit;
        }
    }
     public function responseMsg()
    {
        $postArr = input();
        if (!empty($postArr)){
            if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){   //文本消息
                $fromUsername = $postArr['FromUserName'];   //发送者openid
                $toUserName = $postArr['ToUserName'];       //小程序id
                $textTpl = array(
                    "ToUserName"=>$fromUsername,
                    "FromUserName"=>$toUserName,
                    "CreateTime"=>time(),
                    "MsgType"=>"transfer_customer_service",
                );
                exit(json_encode($textTpl));
            }elseif(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //图文消息
                $fromUsername = $postArr['FromUserName'];   //发送者openid
                $toUserName = $postArr['ToUserName'];       //小程序id
                $textTpl = array(
                    "ToUserName"=>$fromUsername,
                    "FromUserName"=>$toUserName,
                    "CreateTime"=>time(),
                    "MsgType"=>"transfer_customer_service",
                );
                exit(json_encode($textTpl));
            }elseif($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //进入客服动作
                $fromUsername = $postArr['FromUserName'];   //发送者openid

                file_put_contents('log.txt',$fromUsername,FILE_APPEND);
                //查询openid对应的用户是否是会员
                $user = UserModel::where(['openid'=>$fromUsername])->find();
                if(empty($user) === FALSE && $user['is_vip'] == 1){
                    if(empty($nickname) === FALSE && $nickname !== 'undefined'){
                        $content = "尊敬的会员:".$nickname."您好，有什么可以帮您？";
                    }else{
                        $content = "尊敬的会员您好，有什么可以帮您？";
                    }
                }else{
                    if(empty($nickname) === FALSE && $nickname !== 'undefined'){
                        $content = $nickname."您好，有什么可以帮您？";
                    }else{
                        $content = "您好，有什么可以帮您？";
                    }
                }
                file_put_contents('log.txt',$content,FILE_APPEND);
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"text",
                    "text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //php5.4+

                $access_token = \Tools::getaccessToken();
                /*
                 * POST发送https请求客服接口api
                 */
                $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;

                //以'json'格式发送post的https请求
                $output = \Tools::curl($url,'POST',json_encode($data,JSON_UNESCAPED_UNICODE));

                if($output == 0){
                    echo 'success';
                    exit;
                }

            }else{
                exit('aaa');
            }
        }else{
            echo "";
            exit;
        }
    }
    /**
 * 验证微信服务器的签名
 *
 * @param string $token 令牌
 * @param string $timestamp 时间戳
 * @param string $nonce 随机数
 * @param string $signature 微信加密签名
 * @return bool 验证结果
 */
function checkSignature($token, $timestamp, $nonce, $signature)
{
    // 将token、timestamp、nonce按字典序排序
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING);

    // 将三个参数字符串拼接成一个字符串进行sha1加密
    $tmpStr = implode($tmpArr);
    $tmpStr = sha1($tmpStr);

    // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
    return $tmpStr === $signature;
}

}
